﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;

namespace DuBaiCoffee2.Model
{
    public class IOMsg
    {
        private static IOMsg instance;
        private IOMsg() { }

        public static IOMsg Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new IOMsg();
                }
                return instance;
            }
        }
        #region IO通讯
        public bool AllBol = true;
        public bool RobotBol = true;
        public delegate void IOdelegate(string btnName, string tag);
        public IOdelegate iodelegate;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        public static bool IsMsgError = true;
        public bool isRobotBol = false;
        string nostrs = "";
        public Thread All_thr;
        /// <summary>
        /// 左臂点位全部关闭
        /// </summary>
        public void QK()
        {
            try
            {
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotKFJL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotDJBDL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotDJBD2L_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotDJCDL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotQJKFL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotKFJWL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotQDYJL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotDYWCL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotWBTZL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotJBCGL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotJBL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotDYL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotLHL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotLHCCL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotJGTL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotGTWCL_Down();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotZSL_Down();
                Thread.Sleep(100);
            }
            catch (Exception)
            {
                return;
            }
        }
        /// <summary>
        /// 机器人功能按钮关闭
        /// 状态  0 关状态  1 开状态 2 已开机 3 上电 4 下电 5 已使能 6 下使能 7 已运行 8 继续运行 9 已报警 10 已暂停  11已停止 ,12 机械臂状态查询
        /// </summary>
        public void RobotQK(double type = 12)
        {
            try
            {
                if (type == 12 || type == 11)
                {
                    Thread.Sleep(100);
                    RobotModelLeft.Instance.RobotJQRTZYXL_Down();
                }
                if (type == 12 || type == 7)
                {
                    Thread.Sleep(100);
                    RobotModelLeft.Instance.RobotJQRYXL_Down();
                }
                if (type == 12 || type == 9)
                {
                    Thread.Sleep(100);
                    RobotModelLeft.Instance.RobotJQRBJQRL_Down();
                }
                if (type == 12 || type == 3)
                {
                    Thread.Sleep(100);
                    RobotModelLeft.Instance.RobotJQRSDL_Down();
                }
                if (type == 12 || type == 4)
                {
                    Thread.Sleep(100);
                    RobotModelLeft.Instance.RobotJQRXDL_Down();
                }
                if (type == 12 || type == 5)
                {
                    Thread.Sleep(100);
                    RobotModelLeft.Instance.RobotJQRSNL_Down();
                }
                if (type == 12 || type == 6)
                {
                    Thread.Sleep(100);
                    RobotModelLeft.Instance.RobotJQRXSNL_Down();
                }
                if (type == 12 || type == 10)
                {
                    Thread.Sleep(100);
                    RobotModelLeft.Instance.RobotJQRZTL_Down();
                }
                if (type == 12 || type == 8)
                {
                    Thread.Sleep(100);
                    RobotModelLeft.Instance.RobotJQRJXYXL_Down();
                }
                Thread.Sleep(100);
            }
            catch (Exception)
            {
                return;
            }
        }
        public void IOSerial_Robot_Thr()
        {
            try
            {
                bool isRobot = false;
                RobotSerialPortLeft.Instance.Initialization(IPorPortInfo.Instance.RobotIPLeft, IPorPortInfo.Instance.RobotPortLeft);
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotJQRSDL_UP();
                Thread.Sleep(100);
                RobotModelLeft.Instance.RobotJQRSNL_UP();
                Thread.Sleep(100);
                while (!isRobot)
                {
                    isRobot = RobotModelLeft.Instance.LRobotJQRYSN_Sel();
                    Thread.Sleep(100);
                }
                Instance.QK();
                Instance.RobotQK();
                isRobotBol = true;
            }
            catch (Exception)
            {
            }
        }
        public void IOSerial_Thr()
        {
            try
            {
                var ddd = SerialPort.GetPortNames().ToList();
                if (!SerialPort.GetPortNames().ToList().Any(a => a.ToLower().Contains(IPorPortInfo.Instance.PortName)))
                {
                    Thread.Sleep(1000);
                    IOSerial_Thr();
                }
                IOSerialPort.Instance.IceMachineConnect(IPorPortInfo.Instance.PortName, 38400, "", 8, 1);//其他串口通讯
                IOSerialPort.Instance.serialPort.DataReceived += SerialPort_DataReceived;

                Robot_Thr();
                All_thr = new Thread(AllMessages);
                All_thr.IsBackground = true;
                All_thr.Start();
            }
            catch (Exception)
            {
                IOSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        public void Robot_Thr()
        {
            try
            {
                RobotOperate.Read_CSV(); //读取轨迹文件
                RobotOperate.Instance.Robot_Initialisation_double(); //机器人初始化
            }
            catch (Exception)
            {
                Thread.Sleep(100);
                Robot_Thr();
            }
        }
        /// <summary>
        /// PING 通 IP
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public bool PingIP(string IP)
        {
            try
            {
                if (IP.Split('.').Count() < 4) return false;
                Ping pingSender = new Ping();
                PingReply reply = pingSender.Send(IP, 120);//第一个参数为ip地址，第二个参数为ping的时间
                if (reply.Status == IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    //ping不通
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void AllMessages()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        if (Instance.AllBol)
                            IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.AllMessage);
                        Thread.Sleep(100);
                    }
                    catch (Exception)
                    {
                        Thread.Sleep(100);
                    }

                }
            }
            catch (Exception)
            {
                IOSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                var dd = IOSerialPort.Instance.serialPort.BytesToRead;
                byte[] result = new byte[dd];
                IOSerialPort.Instance.serialPort.Read(result, 0, dd);
                string str = "";// $"{DateTime.Now}：\n";
                str += $"{Encoding.ASCII.GetString(result)}";
                for (int i = 0; i < result.Length; i++)
                {
                    str += $"{result[i].ToString("X2")} ";
                }
                MsgShow(str);
                Thread.Sleep(1);
            }
            catch (Exception)
            {
                return;
            }
        }
        public void DigitalMsgBol2(string str)
        {
            try
            {
                var Bol = str.Split(' ');
                bool bol = false;
                if (WuLiaoCoffeeSel.Instance.YBJMilk_Sel_Bol != (Bol[4] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.YBJMilk_Sel_Bol = Bol[4] == "01" ? true : false;

                if (WuLiaoCoffeeSel.Instance.Milk_Sel_Bol != (Bol[6] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.Milk_Sel_Bol = Bol[6] == "01" ? true : false;
                //if (WuLiaoCoffeeSel.Instance.YBJWater_Sel_Bol != (Bol[8] == "01" ? true : false))
                //{
                //    bol = true;
                //}
                //WuLiaoCoffeeSel.Instance.YBJWater_Sel_Bol = Bol[8] == "01" ? true : false;
                //if (WuLiaoCoffeeSel.Instance.Water_Sel_Bol != (Bol[10] == "01" ? true : false))
                //{
                //    bol = true;
                //}
                //WuLiaoCoffeeSel.Instance.Water_Sel_Bol = Bol[10] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.TakeCup_Sel_Bol != (Bol[12] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.TakeCup_Sel_Bol = Bol[12] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.OutMealCup_Sel_Bol != (Bol[14] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.OutMealCup_Sel_Bol = Bol[14] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.LBQFK1_Bol != (Bol[16] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.LBQFK1_Bol = Bol[16] == "01" ? true : false;

                if (WuLiaoCoffeeSel.Instance.CupFeed1_Sel_Bol != (Bol[18] == "01" ? true : false))
                {
                    //if (WuLiaoCoffeeSel.Instance.CupFeed1_Sel_Bol)
                    //    isEmail = true;
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.CupFeed1_Sel_Bol = Bol[18] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.TakeCup2_Sel_Bol != (Bol[20] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.TakeCup2_Sel_Bol = Bol[20] == "01" ? true : false;
                //if (WuLiaoCoffeeSel.Instance.SBX1_Bol != (Bol[22] == "01" ? true : false))
                //{
                //    bol = true;
                //}
                //WuLiaoCoffeeSel.Instance.SBX1_Bol = Bol[22] == "01" ? true : false;

                if (WuLiaoCoffeeSel.Instance.CupFeed2_Sel_Bol != (Bol[24] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.CupFeed2_Sel_Bol = Bol[24] == "01" ? true : false;
                //if (WuLiaoCoffeeSel.Instance.SBS2_Bol != (Bol[26] == "01" ? true : false))
                //{
                //    bol = true;
                //}
                //WuLiaoCoffeeSel.Instance.SBS2_Bol = Bol[26] == "01" ? true : false;
                //if (WuLiaoCoffeeSel.Instance.SBX2_Bol != (Bol[28] == "01" ? true : false))
                //{
                //    bol = true;
                //}
                //WuLiaoCoffeeSel.Instance.SBX2_Bol = Bol[28] == "01" ? true : false;


                if (WuLiaoCoffeeSel.Instance.LBQFK2_Bol != (Bol[30] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.LBQFK2_Bol = Bol[30] == "01" ? true : false;
                if (bol)
                {
                    ClientList clientList = new ClientList();
                    clientList.MsgBol = WuLiaoCoffeeSel.Instance;
                    clientList.code = 2;
                    SocketClients.Instance.client.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList)));
                }
            }
            catch (Exception)
            {
                return;
            }
        }
        public delegate void TestDelegateInvoke();
        private void DelegateInvokeMethod()
        {
            try
            {
                EmailShow emailShow = new EmailShow();
                emailShow.content = MainWindow.EmailError();
                var saves1 = JsonConvert.SerializeObject(emailShow);
                Console.WriteLine(emailShow.content);
                var dd1 = HttpMsg.Instance.sendEmailMsg(saves1);
            }
            catch (Exception)
            {
                return;
            }
        }
        string strlist = "";
        public void MsgShow(string str)
        {
            try
            {
                // Console.WriteLine(str);
                nostrs = "";
                var nostr = str.Split(' ');
                if (nostr.Length >= 2)
                    nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
                for (int i = 1; i < nostr.Count() - 1; i++)
                {
                    nostrs += nostr[i] + " ";
                }
                if (nostrs.Length >= 5)
                {
                    if (nostrs.Substring(0, 5) == "01 05")
                    {
                        Console.WriteLine(str);
                    }
                    else if (nostrs.Substring(0, 5) == "01 04")
                    {
                        strlist = nostrs;
                    }
                    else if (nostrs.Substring(0, 5) == "03 02")
                    {
                        Console.WriteLine(nostrs);
                        var robstr = nostrs.Split(' ');
                        RobotBol = robstr[3] == "01" ? true : false;
                        Console.WriteLine(robstr[3] == "01" ? true : false);
                    }
                    else
                    {
                        if (strlist != "")
                            strlist += nostrs;
                    }
                }
                if (strlist.Split(' ').Count() >= 105)
                {
                    DigitalMsgBol2(strlist);
                    strlist = "";
                }
            }
            catch (Exception ex)
            {
                return;
            }
        }
        #region 完整的
        //public void MsgShow(string str)
        //{
        //    try
        //    {
        //         Console.WriteLine(str);
        //        int count = str.Length / 315;
        //        if (count > 0)
        //        {
        //            var str1 = str.Substring(str.Length - count * 315, 315);
        //            //Console.WriteLine(str1);
        //            if (str1.Split(' ').Count() == 105)
        //            {
        //                DigitalMsgBol2(str1);
        //                if (count > 1)
        //                    MsgShow(str.Substring(str.Length - (count - 1) * 315, (count - 1) * 315));
        //                strlist = "";
        //            }
        //            else
        //            {
        //                var nostr = str1.Split(' ');
        //                int cc = int.TryParse(nostr[0].Substring(nostr[0].Length - 2, 2), out int a) ? a : -1;
        //                if (cc != -1)
        //                {
        //                    nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
        //                    for (int i = 1; i < nostr.Count() - 1; i++)
        //                    {
        //                        nostrs += nostr[i] + " ";
        //                    }
        //                    // Console.WriteLine(nostrs);
        //                    if (nostrs.Substring(0, 5) == "02 04")
        //                    {
        //                        if (nostrs.Count() >= 315)
        //                        {
        //                            DigitalMsgBol2(nostrs);
        //                            nostrs = "";
        //                            strlist = "";
        //                        }
        //                        else
        //                        {
        //                            strlist += nostrs;
        //                            if (strlist.Length >= 315)
        //                            {
        //                                DigitalMsgBol2(strlist);
        //                                nostrs = "";
        //                                strlist = "";
        //                            }
        //                        }
        //                    }
        //                    else
        //                    {
        //                        nostrs = "";
        //                    }
        //                }
        //            }
        //        }
        //        else
        //        {
        //            var nostr = str.Split(' ');
        //            nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
        //            for (int i = 1; i < nostr.Count() - 1; i++)
        //            {
        //                nostrs += nostr[i] + " ";
        //            }
        //            // Console.WriteLine(nostrs);
        //            if (nostrs.Substring(0, 5) == "02 04")
        //            {
        //                //if (nostrs.Count() >= 315)
        //                //{

        //                //    DigitalMsgBol2(nostrs);
        //                //    nostrs = "";
        //                //}
        //                if (nostrs.Count() >= 315)
        //                {
        //                    DigitalMsgBol2(nostrs);
        //                    nostrs = "";
        //                    strlist = "";
        //                }
        //                else
        //                {
        //                    strlist += nostrs;
        //                    if (strlist.Length >= 315)
        //                    {
        //                        DigitalMsgBol2(strlist);
        //                        nostrs = "";
        //                        strlist = "";
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                if (nostrs.Substring(0, 5) == "01 05")
        //                {
        //                    Console.WriteLine(str);
        //                }
        //                else if (nostrs.Substring(0, 5) == "02 04")
        //                {
        //                    // Console.WriteLine(nostrs);
        //                    if (nostrs.Contains("02 04 02 00 01 3C F0"))
        //                    {
        //                        //  DigitalMsgBol.Instance.JBCGJC_Bol = true;
        //                    }
        //                }
        //                else if (nostrs.Substring(0, 5) == "03 02")
        //                {
        //                    Console.WriteLine(nostrs);
        //                    var robstr = nostrs.Split(' ');
        //                    RobotBol = robstr[3] == "01" ? true : false;
        //                    Console.WriteLine(robstr[3] == "01" ? true : false);
        //                }
        //                else
        //                {
        //                    strlist += nostrs;
        //                }
        //                nostrs = "";
        //            }
        //        }

        //    }
        //    catch (Exception)
        //    {
        //        return;
        //    }
        //}
        #endregion

        #endregion
    }
    public class EmailShow
    {
        public string title { get; set; } = "Shortage warning";
        public int deviceId { get; set; } = IPorPortInfo.Instance.DeviceId;
        public string content { get; set; } = "";
        public string fromname { get; set; } = "Coffee Shop";
    }
}
